package com.intelligent.bot.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.bot.base.exception.E;
import com.intelligent.bot.base.result.B;
import com.intelligent.bot.dao.TeamDao;
import com.intelligent.bot.model.Classify;
import com.intelligent.bot.model.Team;
import com.intelligent.bot.model.TeamClassify;
import com.intelligent.bot.model.base.BaseDeleteEntity;
import com.intelligent.bot.model.req.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = E.class)
public class TeamServiceImpl extends ServiceImpl<TeamDao, Team> implements ITeamService {

    @Resource
    ITeamClassifyService teamClassifyService;

    @Override
    public B<Page<Team>> list(TeamGetListReq req) {
        Page<Team> page = new Page<>(req.getPageNumber(), req.getPageSize());
        return B.okBuild(baseMapper.getList(page, req));
    }

    @Override
    public B<Void> add(TeamAddReq req) {
        Long count = this.lambdaQuery().eq(Team::getTeamName, req.getTeamName()).count();
        if(count > 0){
            throw new E("分组名称已存在");
        }
        Team team = BeanUtil.copyProperties(req, Team.class);
        this.save(team);
        return B.okBuild();
    }

    @Override
    public B<Void> update(TeamUpdateReq req) {
        Long count = this.lambdaQuery().eq(Team::getTeamName, req.getTeamName()).ne(Team::getId,req.getId()).count();
        if(count > 0){
            throw new E("分组名称已存在");
        }
        Team team = BeanUtil.copyProperties(req, Team.class);
        this.saveOrUpdate(team);
        return B.okBuild();
    }

    @Override
    public B<Void> delete(BaseDeleteEntity req) {
        this.removeBatchByIds(req.getIds());
        return B.okBuild();
    }

    @Override
    public B<Void> allocation(TeamAllocationReq req) {
        if(!req.getClassifyIds().isEmpty()){
            this.teamClassifyService.lambdaUpdate().eq(TeamClassify::getTeamId, req.getTeamId()).set(TeamClassify::getDeleted,1).update();
            List<TeamClassify> list = new ArrayList<>();
            req.getClassifyIds().forEach(
                    c ->{
                        TeamClassify teamClassify = new TeamClassify();
                        teamClassify.setTeamId(req.getTeamId());
                        teamClassify.setClassifyId(c);
                        list.add(teamClassify);
                    }
            );
            this.teamClassifyService.saveBatch(list);
        }
        return B.okBuild();
    }

    @Override
    public B<List<Classify>> getClassifyList(GetClassifyListReq req) {
        return B.okBuild(teamClassifyService.getClassifyList(req.getTeamId()));
    }
}
